package com.stud.common.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.stud.common.core.domain.model.LoginUser;
import com.stud.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 */
public class MybatisMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增数据执行
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {

        if (Objects.isNull(metaObject.getValue("createTime"))) {
            this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }

        if (Objects.isNull(metaObject.getValue("updateTime"))) {
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }

        LoginUser loginUser = SecurityUtils.getLoginUserTry();
        if (Objects.nonNull(loginUser)) {
            if (Objects.isNull(metaObject.getValue("createBy"))) {
                this.setFieldValByName("createBy", loginUser.getUsername(), metaObject);
            }
            if (Objects.isNull(metaObject.getValue("updateBy"))) {
                this.setFieldValByName("updateBy", loginUser.getUsername(), metaObject);
            }
        }

    }

    //修改时操作
    @Override
    public void updateFill(MetaObject metaObject) {
        if (Objects.isNull(metaObject.getValue("updateTime"))) {
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }

        LoginUser loginUser = SecurityUtils.getLoginUserTry();
        if (Objects.nonNull(loginUser)) {
            if (Objects.isNull(metaObject.getValue("updateBy"))) {
                this.setFieldValByName("updateBy", loginUser.getUsername(), metaObject);
            }
        }
    }
}